package com.dxy.netty.heartbeatcheck;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

import java.nio.charset.StandardCharsets;

/**
 * @Description netty心跳检测服务器处理器
 * @Author dangxianyue
 * @Date 2023/1/6 11:52
 */
public class NettyHeartbeatCheckServerHandler extends ChannelInboundHandlerAdapter {

    private int readIdleTimes = 0;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        String message = buf.toString(StandardCharsets.UTF_8);
        System.out.println("收到客户端消息：" + message);
        if (message.startsWith("PING")) {
            ctx.channel().writeAndFlush("PONG:" + System.currentTimeMillis());
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            String eventType = ""; // 事件类型
            switch (event.state()) {
                case READER_IDLE:
                    eventType = "读空闲";
                    readIdleTimes++;
                    break;
                case WRITER_IDLE:
                    eventType = "写空闲";
                    break;
                case ALL_IDLE:
                    eventType = "读写空闲";
                    break;
            }
            System.out.println("客户端" + ctx.channel().remoteAddress() + "超时事件：" + eventType);
            if (readIdleTimes > 3) {
                System.out.println("[server]读空闲超过3次，关闭连接");
                ctx.channel().writeAndFlush("you are out");
                ctx.channel().close();
            }
        }
    }
}
